package com.atguigu.interceptor;

import com.atguigu.entity.UserInfo;
import com.atguigu.result.Result;
import com.atguigu.result.ResultCodeEnum;
import com.atguigu.util.WebUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 杨林
 * @create 2022-09-25 16:59 星期日
 * description:定义登录拦截器  如果登录则 放行
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //获取session中的USER信息
        UserInfo userInfo = (UserInfo)request.getSession().getAttribute("USER");

        //判断用户是否已经登录
        if (userInfo != null){ //表示用户已经登录  放行用户请求
            return true;
        }else{
            //跳转到登录页面
            Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
            WebUtil.writeJSON(response,result);
            return false;
        }
    }
}
